package JUC;

class Aircondition{
    private int number = 0;

    //老版写法
    public synchronized void increment() throws InterruptedException {
        //1.判断
        while (number != 0){
            this.wait();
        }
        //2.干活
        number++;
        System.out.println(Thread.currentThread().getName()+"\t"+number);
        //3通知
        this.notifyAll();

    }

    public synchronized void decrement() throws InterruptedException {
        //1.判断
        while (number == 0){
            this.wait();
        }
        //2.干活
        number--;
        //3通知
        System.out.println(Thread.currentThread().getName()+"\t"+number);
        this.notifyAll();
    }

}
/**
 * 题目：现在两个线程，可以操作初始值为零的一个变量，
 * 实现一个线程对该变量加1，一个线程对该变量-1，
 * 实现交替，来10轮，变量初始值为0.
 *      1.高内聚低耦合前提下，线程操作资源类
 *      2.判断/干活/通知
 *      3.多线程交互下（也就是wait和notify公用），防止虚假唤醒(判断只能用while，不能用if)
 * 知识小总结：多线程编程套路+while判断+新版写法
 */

public class ThreadWaitNotifyDemo {
    public static void main(String[] args) {

        Aircondition aircondition = new Aircondition();

        new Thread(()->{
                    //insert your code here
            for (int i = 0; i < 10; i++) {
                try {
                    aircondition.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
                },"A").start();

        new Thread(()->{
                    //insert your code here
            for (int i = 0; i < 10; i++) {
                try {
                    aircondition.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
                },"B").start();
        new Thread(()->{
                    //insert your code here
            for (int i = 0; i < 10; i++) {
                try {
                    aircondition.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
                },"C").start();

        new Thread(()->{
                    //insert your code here
            for (int i = 0; i < 10; i++) {
                try {
                    aircondition.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
                },"D").start();
    }

}
